# This file makes the 'app' directory a Python package and contains the application factory.
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import os
from flask_cors import CORS
# 导入Config类
from config import Config

# 1. 初始化扩展
db = SQLAlchemy()
migrate = Migrate()

def create_app(config_class=None):
    """
    应用工厂函数
    """
    app = Flask(__name__)
    
    # --- 核心修正：从config.py加载配置 ---
    app.config.from_object(Config)
    # --- 修正结束 ---

    # 2. 将扩展实例与app关联
    db.init_app(app)
    migrate.init_app(app, db)
    CORS(app) # Enable CORS for all routes

    # 在应用上下文中创建数据库表
    with app.app_context():
        # 我们需要先导入模型，确保create_all知道要创建什么表
        from . import models 
        db.create_all()

    # 3. 导入并注册蓝图（这是关键的改动）
    #    必须在db实例化并初始化后，再导入这些会用到db的模块
    from .routes import main_bp
    app.register_blueprint(main_bp)

    from .models import Signal, ManualTrade

    return app 